<template>
  <div class="profile-page">
    <!-- 用户信息卡片 -->
    <div class="user-card" v-if="userStore.user">
      <div class="user-info">
        <div class="avatar">
          <img 
            v-if="userStore.user.avatar_url" 
            :src="userStore.user.avatar_url" 
            :alt="userStore.user.nickname"
          />
          <van-icon v-else name="user-o" />
        </div>
        <div class="user-details">
          <h2 class="username">{{ userStore.user.nickname }}</h2>
          <p class="user-id">ID: {{ userStore.user.id }}</p>
          <div class="vip-badge" v-if="userStore.user.vip_level > 0">
            <van-icon name="diamond" />
            <span>VIP{{ userStore.user.vip_level }}</span>
          </div>
        </div>
      </div>
      
      <!-- 配额信息 -->
      <div class="quota-section">
        <div class="quota-item">
          <div class="quota-number">{{ userStore.user.daily_quota - userStore.user.used_quota }}</div>
          <div class="quota-label">剩余次数</div>
        </div>
        <div class="quota-divider"></div>
        <div class="quota-item">
          <div class="quota-number">{{ userStore.user.daily_quota }}</div>
          <div class="quota-label">每日限额</div>
        </div>
        <div class="quota-divider"></div>
        <div class="quota-item">
          <div class="quota-number">{{ totalGenerated }}</div>
          <div class="quota-label">累计生成</div>
        </div>
      </div>
    </div>

    <!-- 功能菜单 -->
    <div class="menu-section">
      <van-cell-group>
        <van-cell 
          title="我的作品" 
          icon="photo-o" 
          is-link 
          @click="goToHistory"
        />
        <van-cell 
          title="个人资料" 
          icon="edit" 
          is-link 
          @click="editProfile"
        />
        <van-cell 
          title="升级VIP" 
          icon="diamond-o" 
          is-link 
          @click="upgradeVip"
          v-if="userStore.user?.vip_level === 0"
        />
        <van-cell 
          title="使用帮助" 
          icon="question-o" 
          is-link 
          @click="showHelp"
        />
        <van-cell 
          title="意见反馈" 
          icon="chat-o" 
          is-link 
          @click="showFeedback"
        />
        <van-cell 
          title="关于我们" 
          icon="info-o" 
          is-link 
          @click="showAbout"
        />
      </van-cell-group>
    </div>

    <!-- 设置菜单 -->
    <div class="settings-section">
      <van-cell-group>
        <van-cell title="清理缓存" icon="delete-o" @click="clearCache" />
        <van-cell title="退出登录" icon="logout" @click="logout" />
      </van-cell-group>
    </div>

    <!-- 版本信息 -->
    <div class="version-info">
      <p>喵趣AI v1.0.0</p>
      <p>让每只猫咪都有专属风格</p>
    </div>

    <!-- 编辑资料弹窗 -->
    <van-popup 
      v-model:show="showEditPopup" 
      position="bottom" 
      :style="{ height: '60%' }"
    >
      <div class="edit-popup">
        <div class="popup-header">
          <van-button 
            type="default" 
            size="small" 
            @click="showEditPopup = false"
          >
            取消
          </van-button>
          <h3>编辑资料</h3>
          <van-button 
            type="primary" 
            size="small" 
            @click="saveProfile"
            :loading="savingProfile"
          >
            保存
          </van-button>
        </div>
        
        <div class="popup-content">
          <van-form>
            <van-field
              v-model="editForm.nickname"
              label="昵称"
              placeholder="请输入昵称"
              maxlength="20"
              show-word-limit
            />
            <van-field
              v-model="editForm.phone"
              label="手机号"
              placeholder="请输入手机号"
              type="tel"
            />
            <van-field
              v-model="editForm.email"
              label="邮箱"
              placeholder="请输入邮箱"
              type="email"
            />
          </van-form>
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { updateProfileApi } from '../api/auth'
import { Toast, Dialog } from 'vant'

const router = useRouter()
const userStore = useUserStore()

const showEditPopup = ref(false)
const savingProfile = ref(false)
const totalGenerated = ref(0) // 这个需要从API获取

const editForm = ref({
  nickname: '',
  phone: '',
  email: ''
})

// 计算属性
const canGenerate = computed(() => userStore.canGenerate)

// 去历史记录页面
const goToHistory = () => {
  router.push('/history')
}

// 编辑个人资料
const editProfile = () => {
  if (userStore.user) {
    editForm.value = {
      nickname: userStore.user.nickname,
      phone: userStore.user.phone || '',
      email: userStore.user.email || ''
    }
  }
  showEditPopup.value = true
}

// 保存个人资料
const saveProfile = async () => {
  savingProfile.value = true
  
  try {
    const result = await updateProfileApi(editForm.value)
    
    if (result.success) {
      // 更新本地用户信息
      await userStore.getProfile()
      showEditPopup.value = false
      Toast.success('保存成功')
    }
  } catch (error: any) {
    Toast.fail(error.message || '保存失败')
  } finally {
    savingProfile.value = false
  }
}

// 升级VIP
const upgradeVip = () => {
  Dialog.alert({
    title: 'VIP特权',
    message: `
      <div style="text-align: left; line-height: 1.6;">
        <p><strong>VIP专享特权：</strong></p>
        <p>• 每日生成次数 20次</p>
        <p>• 专属高级风格模板</p>
        <p>• 优先处理队列</p>
        <p>• 无水印高清下载</p>
        <p>• 专属客服支持</p>
        <br>
        <p style="color: #ff6b6b;"><strong>限时优惠：￥19.9/月</strong></p>
      </div>
    `,
    allowHtml: true,
    confirmButtonText: '立即升级'
  }).then(() => {
    Toast('支付功能开发中...')
  })
}

// 使用帮助
const showHelp = () => {
  Dialog.alert({
    title: '使用帮助',
    message: `
      <div style="text-align: left; line-height: 1.6;">
        <p><strong>1. 上传照片</strong></p>
        <p>选择一张清晰的猫咪照片，建议正面拍摄</p>
        <br>
        <p><strong>2. 选择风格</strong></p>
        <p>从多种AI风格中选择您喜欢的类型</p>
        <br>
        <p><strong>3. 等待生成</strong></p>
        <p>AI将在1-3分钟内完成图片生成</p>
        <br>
        <p><strong>4. 保存分享</strong></p>
        <p>生成完成后可下载或分享给好友</p>
      </div>
    `,
    allowHtml: true
  })
}

// 意见反馈
const showFeedback = () => {
  Toast('功能开发中...')
}

// 关于我们
const showAbout = () => {
  Dialog.alert({
    title: '关于喵趣AI',
    message: `
      <div style="text-align: center; line-height: 1.6;">
        <p><strong>喵趣AI</strong></p>
        <p>专为猫咪爱好者打造的AI图片生成工具</p>
        <br>
        <p>让每只猫咪都有专属的创意风格</p>
        <p>用AI技术展现猫咪的独特魅力</p>
        <br>
        <p style="color: #666; font-size: 12px;">
          技术支持：GPT-4 + Stable Diffusion<br>
          版本：v1.0.0
        </p>
      </div>
    `,
    allowHtml: true
  })
}

// 清理缓存
const clearCache = () => {
  Dialog.confirm({
    title: '清理缓存',
    message: '确定要清理应用缓存吗？这将清除本地存储的图片缓存。'
  }).then(() => {
    // 清理本地缓存
    localStorage.removeItem('image_cache')
    Toast.success('缓存已清理')
  })
}

// 退出登录
const logout = () => {
  Dialog.confirm({
    title: '退出登录',
    message: '确定要退出登录吗？'
  }).then(async () => {
    await userStore.logout()
    Toast.success('已退出登录')
    router.push('/login')
  })
}

// 获取统计数据
const loadStats = async () => {
  // TODO: 从API获取用户统计数据
  totalGenerated.value = 15 // 模拟数据
}

onMounted(() => {
  loadStats()
})
</script>

<style scoped>
.profile-page {
  min-height: 100vh;
  background: #f7f8fa;
  padding-bottom: 20px;
}

.user-card {
  background: linear-gradient(135deg, #6366f1 0%, #8b5cf6 100%);
  color: white;
  padding: 30px 20px;
  position: relative;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 30px;
}

.avatar {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar .van-icon {
  font-size: 32px;
  color: white;
}

.user-details h2 {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 4px;
}

.user-id {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 8px;
}

.vip-badge {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  background: linear-gradient(45deg, #ffd700, #ffed4a);
  color: #333;
  padding: 4px 8px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: bold;
}

.quota-section {
  display: flex;
  justify-content: space-around;
  align-items: center;
  background: rgba(255, 255, 255, 0.15);
  border-radius: 16px;
  padding: 20px;
  backdrop-filter: blur(10px);
}

.quota-item {
  text-align: center;
}

.quota-number {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 4px;
}

.quota-label {
  font-size: 12px;
  opacity: 0.8;
}

.quota-divider {
  width: 1px;
  height: 40px;
  background: rgba(255, 255, 255, 0.3);
}

.menu-section,
.settings-section {
  margin: 20px 16px;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.version-info {
  text-align: center;
  color: #999;
  font-size: 12px;
  line-height: 1.5;
  margin-top: 30px;
}

.edit-popup {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #eee;
}

.popup-header h3 {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.popup-content {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
}
</style>